import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { gql, useQuery } from '@apollo/client';

import Loading from '@kuiper-components/loading';

import ChartPanel from '../ChartPanel';
import s from './Asset.module.css';
import { name } from '../../../../../../package.json';

const QUERY_GQL = gql`
	query {
		AssetMany {
			_id
			target
			job {
				note
				_id
			}
			result {
				_id
				result {
					warningCount
					warnings {
						_id
					}
				}
			}
		}
	}
`;
export default function Asset({ className, data, taskIdMap }) {
	const lastestCount = window?.kuiper?.app?.config[name]?.homeLastestCount;

	const { data: assetData, loading } = useQuery(QUERY_GQL);

	const chartLineData = new Array(10).fill(0);
	for (let i = 0; i < data.length; i++) {
		for (let j = 0; j < lastestCount; j++) {
			chartLineData[j] =
				chartLineData[j] + (data[i][j]?.result?.warningCount || 0);
		}
	}

	const lineData = chartLineData.reverse();

	let total = 0;
	const tableData = (assetData?.AssetMany || [])
		.map(item => {
			const target = item?.target;
			const warningCount = item?.result?.result?.warningCount || 0;
			total += warningCount;
			return {
				target,
				note: item?.job?.note || '',
				sum: warningCount,
				link: taskIdMap[target]?.resultId
					? `/asset/asset/detail/${taskIdMap[target]?.resultId}`
					: undefined,
			};
		})
		.filter(x => x.sum > 0)
		.sort((a, b) => b.sum - a.sum);

	const columns = [
		{ name: 'target', label: '监测资产' },
		{ name: 'sum', label: '资产变动数', width: 88 },
	];

	return (
		<Loading hasData show={loading}>
			<ChartPanel
				className={cn(className, s.asset)}
				key="asset"
				title="资产变动"
				type="asset"
				desc="以下数据为最近一次的资产变动监测结果，按资产变动数从高到低排序。"
				link="/asset/asset/overview"
				tableData={tableData}
				chartData={lineData}
				num={total}
				tooltipText="总资产最近十次监测结果趋势图"
				numLabel="资产变动总数"
				tableColumns={columns}
				chartLabel="资产变动趋势"
				color="#FAAF2C"
			/>
		</Loading>
	);
}

Asset.propTypes = {
	className: PropTypes.string,
	data: PropTypes.array,
	taskIdMap: PropTypes.array,
};

Asset.defaultProps = {
	className: s.asset,
};
